package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 74. 搜索二维矩阵
 * @date 2025/5/14 15:03
 */
public class E74 {

    /**
     * 方法一：二分查找
     *
     * @param matrix 二维数组
     * @param target 目标值
     * @return 是否存在
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        int n = matrix.length, m = matrix[0].length, totalLen = n * m;
        int left = 0, right = totalLen - 1;
        while (left <= right) {
            int median = (left + right) >>> 1;
            int i = median / m, j = median % m;
            if (target < matrix[i][j]) {
                right = median - 1;
            } else if (matrix[i][j] < target) {
                left = median + 1;
            } else {
                return true;
            }
        }
        return false;
    }
}
